import { useEffect, useState } from 'react';
import { Line } from '@ant-design/plots';
import {
  LightFilter,
  ProCard,
  ProFormDateRangePicker,
} from '@ant-design/pro-components';
import dayjs from 'dayjs';

import request from '@/utils/request';
import { afterDay, pastDay, tsFmtLongDate } from '@/utils/time';

import TrendTable from './TrendTable';

const lineConfig = {
  xField: 'date',
  yField: 'value',
  seriesField: 'category',
  height: 300,
  autoFit: false,
  xAxis: {
    type: 'time',
  },
};

const fieldType = {
  good_count: '无需重构',
  medium_count: '建议重构',
  optimize_count: '强烈建议重构',
};

const Trend = ({ url }) => {
  const [lineData, setLineData] = useState([]);
  const [dateRange, setDateRange] = useState([pastDay(8), dayjs()]);
  const startDate = tsFmtLongDate(dateRange[0]);
  const endDate = tsFmtLongDate(dateRange[1]);

  useEffect(() => {
    request('/api/trend', {
      method: 'POST',
      data: { url, start_date: startDate, end_date: endDate },
    }).then((res) => {
      const result = res.data
        ?.map((item) => {
          return ['good_count', 'medium_count', 'optimize_count'].map(
            (field) => ({
              value: item[field],
              date: tsFmtLongDate(item.created_at),
              category: fieldType[field],
            }),
          );
        })
        .flat();
      setLineData(result);
    });
  }, [url, dateRange]);

  return (
    <ProCard
      ghost
      extra={
        <LightFilter
          syncToUrl={true}
          initialValues={{
            date_range: dateRange,
          }}
        >
          <ProFormDateRangePicker
            label="时间范围"
            name="date_range"
            value={dateRange}
            allowClear={false}
            fieldProps={{
              placement: 'bottomLeft',
              disabledDate: (c) =>
                c < pastDay(180).startOf('day') ||
                c > afterDay(1).startOf('day'),
              ranges: {
                本周: [dayjs().startOf('week'), dayjs()],
                '过去 7 天': [pastDay(7), dayjs()],
                '过去 30 天': [pastDay(30), dayjs()],
                '过去 180 天': [pastDay(180), dayjs()],
              },
            }}
            onChange={setDateRange}
          />
        </LightFilter>
      }
    >
      <Line data={lineData} {...lineConfig} />
      <TrendTable url={url} startDate={startDate} endDate={endDate} />
    </ProCard>
  );
};

export default Trend;
